from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import re
import xlwt
import xlrd
import xlutils.copy
import pandas as pd

filename = 'config/tiku.xls'


def readline():
    wb = xlrd.open_workbook(filename, formatting_info=True)  # 打开excel，保留文件格式
    sheet1 = wb.sheet_by_index(0)  # 获取第一张表
    nrows = sheet1.nrows  # 获取总行数
    return nrows


def write(question, answer, details, a=None,
          b=None, c=None, d=None, e=None, f=None):
    data = xlrd.open_workbook(filename)
    ws = xlutils.copy.copy(data)  # 复制之前表里存在的数据
    table = ws.get_sheet(0)
    nownrows = readline()
    table.write(nownrows, 0, label=question)  # 最后一行追加数据
    table.write(nownrows, 1, label=answer)
    table.write(nownrows, 2, label=details)
    table.write(nownrows, 3, label=a)
    table.write(nownrows, 4, label=b)
    table.write(nownrows, 5, label=c)
    table.write(nownrows, 6, label=d)
    table.write(nownrows, 7, label=e)
    table.write(nownrows, 8, label=f)
    ws.save(filename)  # 保存的有旧数据和新数据
    print('题目数据已经加入题库')


def index(track, school, name, stu_num, college, mailbox):
    # 打开答题页面
    driver.get('https://webapp-ali.ynurl.cn/s/2022/lxj/gxzswd/index.html')
    time.sleep(2)
    # 点击答题  专科（高职）学生和研究生
    driver.find_element_by_xpath('/html/body/div[1]/div/div[2]/div').click()
    time.sleep(2)
    # 选择学校
    driver.find_element_by_xpath(
        f'/html/body/div[2]/div/div[2]/div[{track}]/select/option[{school}]').click()
    time.sleep(2)
    # 下一页
    driver.find_element_by_xpath(
        '/html/body/div[2]/div/div[2]/div[6]/img').click()
    time.sleep(2)
    # 非毕业生
    driver.find_element_by_xpath(
        '/html/body/div[3]/div/div[2]/div[2]/select/option[3]').click()
    # 姓名
    time.sleep(1)
    driver.find_element_by_xpath(
        '/html/body/div[3]/div/div[2]/div[3]/input').clear()
    driver.find_element_by_xpath(
        '/html/body/div[3]/div/div[2]/div[3]/input').send_keys(name)
    # 学号
    time.sleep(1)
    driver.find_element_by_xpath(
        '/html/body/div[3]/div/div[2]/div[4]/input').clear()
    driver.find_element_by_xpath(
        '/html/body/div[3]/div/div[2]/div[4]/input').send_keys(stu_num)
    # 学院
    time.sleep(1)
    driver.find_element_by_xpath(
        '/html/body/div[3]/div/div[2]/div[5]/input').clear()
    driver.find_element_by_xpath(
        '/html/body/div[3]/div/div[2]/div[5]/input').send_keys(college)
    # 邮箱
    time.sleep(1)
    driver.find_element_by_xpath(
        '/html/body/div[3]/div/div[2]/div[6]/input').clear()
    driver.find_element_by_xpath(
        '/html/body/div[3]/div/div[2]/div[6]/input').send_keys(mailbox)
    # 进入答题
    time.sleep(1)
    element1 = driver.find_element_by_xpath(
        '/html/body/div[3]/div/div[2]/div[8]/img[1]')
    driver.execute_script("arguments[0].click();", element1)


def answer(id):
    time.sleep(3)
    ans_option = ''
    # 问题
    question = driver.find_element_by_xpath(f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[2] '
                                            ).get_attribute('innerText').replace('10、', '').replace(
        '11、', '').replace('12、', '').replace('13、', '').replace('14、', '').replace('15、', '').replace('16、', '').replace('17、', '').replace('18、', '').replace('19、', '').replace('20、', '').replace(
        '21、', '').replace('22、', '').replace('23、', '').replace('24、', '').replace('25、', '').replace('26、', '').replace('27、', '').replace('28、', '').replace('29、', '').replace('30、', '').replace(
        '1、', '').replace('2、', '').replace('3、', '').replace('4、', '').replace('5、', '').replace('6、', '').replace('7、', '').replace('8、', '').replace('9、', '')
    # 答案/html/body/div[4]/form/div/div[2]/div/div[1]/div[4]
    key_str = driver.find_element_by_xpath(
        f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[4]').get_attribute('innerText')
    print('提示', key_str)
    time.sleep(2)
    # 选项A
    ans_a = driver.find_element_by_xpath(
        f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[3]/div[1]/label').get_attribute('innerText').replace('A、', '')
    # print('选项A', ans_a)
    if re.findall(ans_a, key_str):
        if not re.findall(ans_a, question):
            driver.find_element_by_xpath(
                f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[3]/div[1]/label').click()
            print('点击A', ans_a)
            ans_option = 'A'
    # 选项B
    ans_b = driver.find_element_by_xpath(f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[3]/div[2]/label').get_attribute('innerText').replace(
        'B、', '')
    # print('选项B', ans_b)
    if re.findall(ans_b, key_str):
        if not re.findall(ans_b, question):
            driver.find_element_by_xpath(
                f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[3]/div[2]/label').click()
            print('点击B', ans_b)
            ans_option = 'B'
    # 选项C
    try:
        ans_c = driver.find_element_by_xpath(
            f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[3]/div[3]/label').get_attribute('innerText').replace('C、', '')
        # print('选项C', ans_c)
        if re.findall(ans_c, key_str):
            if not re.findall(ans_c, question):
                driver.find_element_by_xpath(
                    f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[3]/div[3]/label').click()
                print('点击C', ans_c)
                ans_option = 'C'
    except BaseException:
        ans_c = ''
    # 选项D
    try:
        ans_d = driver.find_element_by_xpath(
            f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[3]/div[4]/label').get_attribute('innerText').replace('D、', '')
        # print('选项D', ans_d)
        if re.findall(ans_d, key_str):
            if not re.findall(ans_d, question):
                driver.find_element_by_xpath(
                    f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[3]/div[4]/label').click()
                print('点击D', ans_d)
                ans_option = 'D'
    except BaseException:
        ans_d = ''
    return question, ans_option, key_str, ans_a, ans_b, ans_c, ans_d


def search(id):
    # 问题
    question = driver.find_element_by_xpath(f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[2] '
                                            ).get_attribute('innerText').replace('10、', '').replace(
        '11、', '').replace('12、', '').replace('13、', '').replace('14、', '').replace('15、', '').replace('16、', '').replace(
        '17、', '').replace('18、', '').replace('19、', '').replace('20、', '').replace('21、', '').replace('22、', '').replace('23、', '').replace('24、', '').replace('25、', '').replace('26、',
                                                                                                                                                                                   '').replace('27、', '').replace('28、', '').replace('29、', '').replace('30、', '').replace(
        '1、', '').replace('2、', '').replace('3、', '').replace('4、', '').replace('5、', '').replace('6、', '').replace(
        '7、', '').replace('8、', '').replace('9、', '')
    print('搜索第', id, '题目', question)
    # 读取题库数据
    data_tk = pd.read_excel('config/tiku.xls', sheet_name='tiku', index_col=0)
    try:
        # 匹配题库数据
        search_tk = data_tk.loc[question]
        # 题库数据处理
        search_tk_str = str(search_tk).split('\n')
        # 提取答案
        search_tk_key = search_tk_str[0][-1]
        print('答案搜索成功', search_tk_key)
        return search_tk_key
    except BaseException:
        search_tk_key = ''
        return search_tk_key


def search_answer(id, key):
    time.sleep(2)
    if key == 'A':
        driver.find_element_by_xpath(
            f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[3]/div[1]/label').click()
    elif key == 'B':
        driver.find_element_by_xpath(
            f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[3]/div[2]/label').click()
    elif key == 'C':
        driver.find_element_by_xpath(
            f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[3]/div[3]/label').click()
    elif key == 'D':
        driver.find_element_by_xpath(
            f'/html/body/div[4]/form/div/div[2]/div/div[{id}]/div[3]/div[4]/label').click()


if __name__ == '__main__':
    print('=========程序初始化中，请不要关闭打开的浏览器=========')
    print('''==========================================
    1.程序依赖于Chrome浏览器，请先安装
    2.自动化程序仅用于交流学习，不得用于商业用途，请在下载后24H内删除，否则后果与作者无关
    3.如果在运行中出现bug或交流学习请到[ov小站反馈]
    4.[ov小站网址]:https://valley-ov.cn
    5.[微信公众号]:百晓晓
==========================================''')
    track = int(input(
        '======================\nA赛道[2]\nB赛道[3]\nC赛道[4]\n======================\n请选择赛道的编号:'))
    if track == 2:
        print('A赛道')
        g_school = [
            "昆明理工大学",
            "云南经济管理学院",
            "云南师范大学",
            "云南农业大学",
            "云南工商学院",
            "云南财经大学",
            "云南民族大学",
            "云南大学",
            "西南林业大学",
            "云南交通职业技术学院",
            "云南大学滇池学院",
            "昆明冶金高等专科学校",
            "昆明学院",
            "大理大学"]
        for i in range(len(g_school)):
            print('[', i + 2, ']', g_school[i])
        pass
    elif track == 3:
        print('B赛道')
        g_school = [
            "昆明医科大学",
            "昆明城市学院",
            "丽江文化旅游学院",
            "昆明文理学院",
            "曲靖师范学院",
            "云南国土资源职业学院",
            "云南林业职业技术学院",
            "楚雄师范学院",
            "红河学院",
            "昆明工业职业技术学院",
            "云南中医药大学",
            "昆明医科大学海源学院",
            "玉溪师范学院",
            "云南经贸外事职业学院",
            "云南机电职业技术学院",
            "云南开放大学（云南国防工业职业技术学院）",
            "昆明卫生职业学院",
            "云南旅游职业学院",
            "云南农业职业技术学院",
            "文山学院",
            "滇西科技师范学院",
            "保山学院",
            "云南新兴职业学院",
            "云南能源职业技术学院",
            "云南艺术学院",
            "云南工程职业学院",
            "普洱学院",
            "昆明理工大学津桥学院",
            "滇西应用技术大学",
            "红河卫生职业学院",
            "德宏职业学院",
            "昭通学院"]
        for i in range(len(g_school)):
            print('[', i + 2, ']', g_school[i])
    elif track == 4:
        print('C赛道')
        g_school = [
            "玉溪农业职业技术学院",
            "云南交通运输职业学院",
            "德宏师范高等专科学校",
            "云南艺术学院文华学院",
            "保山中医药高等专科学校",
            "丽江师范高等专科学校",
            "曲靖医学高等专科学校",
            "楚雄医药高等专科学校",
            "云南商务职业学院",
            "云南财经职业学院",
            "云南医药健康职业学院",
            "西双版纳职业技术学院",
            "云南轻纺职业学院",
            "云南水利水电职业学院",
            "云南体育运动职业技术学院",
            "昆明幼儿师范高等专科学校",
            "云南文化艺术职业学院",
            "云南城市建设职业学院",
            "昆明铁道职业技术学院",
            "大理护理职业学院",
            "云南警官学院",
            "云南外事外语职业学院",
            "云南工贸职业技术学院",
            "大理农林职业技术学院",
            "昭通卫生职业学院",
            "云南锡业职业技术学院",
            "云南司法警官职业学院",
            "昆明艺术职业学院",
            "云南三鑫职业技术学院",
            "曲靖职业技术学院",
            "云南特殊教育职业学院",
            "红河职业技术学院",
            "云南科技信息职业学院",
            "云南理工职业学院",
            "云南现代职业技术学院"]
        for i in range(len(g_school)):
            print('[', i + 2, ']', g_school[i])
    else:
        input('====赛道选择错误====')
    school = int(input('请输入学校编号:'))
    name = input('请输入姓名:')
    stu_num = input('请输入学号:')
    college = input('请输入学院:')
    mailbox = input('请输入邮箱:')
    count = int(input('请输入需要挑战成功多少次:'))
    print('==========================================\n正在打开网页，请稍等...')
    options = Options()
    # 屏蔽webdriver特征
    # options.add_argument('--headless')
    options.add_argument('--window-size=340,900')  # 设置窗口大小
    options.add_argument('--window-position=0,0')  # 设置窗口位置
    options.add_argument('--disable-gpu')
    options.add_argument("--disable-blink-features")
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.add_experimental_option(
        'excludeSwitches', [
            'enable-logging', 'enable-automation'])
    driver = webdriver.Chrome('config/chromedriver.exe', options=options)
    index(track, school, name, stu_num, college, mailbox)
    c0 = 1
    while c0 <= count:
        for i in range(30):
            # 题库搜索
            if i + 1 == 11 or i + 1 == 21:
                print('=====等待中，等进入下一个阶段====')
                time.sleep(10)
            key = search(i + 1)
            if key != '':
                search_answer(i + 1, key)
                time.sleep(1)
                element1 = driver.find_element_by_xpath(
                    '/html/body/div[4]/form/div/div[3]/img[2]')
                driver.execute_script("arguments[0].click();", element1)
            else:
                question, ans_option, key_str, ans_a, ans_b, ans_c, ans_d = answer(
                    i + 1)
                time.sleep(1)
                element1 = driver.find_element_by_xpath(
                    '/html/body/div[4]/form/div/div[3]/img[2]')
                driver.execute_script("arguments[0].click();", element1)
                try:
                    alert = driver.switch_to.alert
                    print(alert.text)
                    if alert.text == '请选择答案！':
                        input('答题失败，请根据提示手动答题')
                except BaseException:
                    pass
                try:
                    element2 = driver.find_element_by_xpath(
                        '/html/body/div[7]/div/div/div/div[2]/img')
                    driver.execute_script("arguments[0].click();", element2)
                    error_text = driver.find_element_by_xpath('/html/body/div[7]/div/div/div/div[1]').get_attribute(
                        'innerText')
                    print(error_text)
                    if error_text[:4] == '正确答案':
                        print(error_text[-1])
                        write(question,
                              error_text[-1],
                              key_str,
                              ans_a,
                              ans_b,
                              ans_c,
                              ans_d)
                except BaseException:
                    print('答题正确')
                    write(
                        question,
                        ans_option,
                        key_str,
                        ans_a,
                        ans_b,
                        ans_c,
                        ans_d)
            time.sleep(2)
        try:
            driver.find_element_by_xpath(
                '/html/body/div[9]/div/div/img').click()
            print('挑战失败')
        except BaseException:
            pass
        try:
            driver.find_element_by_xpath(
                '/html/body/div[5]/div/div/div/img').click()
            print('==========================================')
            print('挑战成功', c0, '次')
            print('==========================================')
            c0 += 1
        except BaseException:
            pass
    driver.quit()
    input('===回车结束===')
